#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from utility import tools
from model.user import UserVo
from event import event_type
from command import command
import logging
from utility.api_security import APISecurity

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class UserQueryAPI(Resource):
    """
    获取用户详情资料
    :request: get
    ：param id：用户id
    :returns: json string
    """
    def get(self):
        try:
            params = tools.get_params(request)
            odoo = OdooManager().get_instance()
            user = odoo.env['res.users'].browse(int(params.get('id')))[0]
            user_vo = UserVo()
            user_vo.name = user.name
            user_vo.email = user.email
            user_vo.mobile = user.mobile
            return jsonify({'code': 0, 'msg': 'success', 'data': tools.class_to_dict(user_vo)})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class UserInfoByToken (Resource):
    """
    根据token获取用户信息
    """
    def get(self):
        payload = APISecurity().verify_access_token()
        if not payload:
            return jsonify({'code': 901, 'msg': error_code[901]})
        try:
            userId = payload['aud']
            odoo = OdooManager().get_instance()
            user = odoo.env['res.users'].browse(int(userId))[0]
            userData = UserVo()
            userData.userName = user.name
            userData.userId = userId
            userData.email = user.email
            userData.phonenumber = user.mobile
            userData.hospitalId = user.company_id.id
            userData.postName = user.employee_id.name
            # userData.postId_ = user.employee_id.id,
            userdata = tools.class_to_dict(userData)
            userdata['postId'] = user.employee_id.id
            return jsonify({
                'code': 0,
                'msg': 'success',
                'data': {
                    'user': userdata
                }
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({
                'code': 100,
                'msg': error_code[100]
            })

class UserCreateAPI(Resource):
    """
    新增用户
    :request: post
    ：param name：姓名
    ：param login：登录用户名
    ：param email：邮箱
    ：param mobile：手机号码
    :returns: json string
    """
    def post(self):
        try:
            params = tools.get_params(request)
            create_command = command.CreateUserCommand(params.get('name'), params.get('login'), params.get('email'), params.get('mobile'))
            command_bus = MessageBusManager().get_command_bus()
            user_id = command_bus.handle(create_command)  # 发布命令

            # 记录操作日志
            create_event = event_type.OperationLogEvent('新增用户', '用户id：{}'.format(user_id))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {'user_id': user_id}})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})